package com.yksj.healthtalk.ui.doctorstation;

import org.json.JSONException;
import org.json.JSONObject;
import org.universalimageloader.core.ImageLoader;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.yksj.healthtalk.comm.CommonExplainActivity;
import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog;
import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog.OnDilaogClickListener;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.entity.DoctorOrderDeatils;
import com.yksj.healthtalk.entity.DoctorPatient;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.ObjectHttpResponseHandler;
import com.yksj.healthtalk.net.http.RequestParams;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.doctor.DoctorServiceActivity;
import com.yksj.healthtalk.utils.DataParseUtil;
import com.yksj.healthtalk.utils.FriendHttpUtil;
import com.yksj.healthtalk.utils.TimeUtil;
import com.yksj.healthtalk.utils.ToastUtil;
/**
 * 已预约-已支付-查看详情
 * @author Administrator
 */
public class DoctorMarkedService extends Fragment  implements OnClickListener{

	private View mView;
	private DoctorOrderDeatils deatils;
	private DoctorPatient mEntity;
	private Button mButton;
	private Button agreeYanshi;//同意
	private Button refuseYanshi;//拒绝
	private String Type="";//类型
	private boolean isYanShi=false;//false 延时  true退订
	private String CANCEL_REASON;
	private TextView prompt;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.doctor_marked_service,null);
		
		initView();
		
		return mView;
	}
	

	private void initView() {
		mView.findViewById(R.id.title_back).setOnClickListener(this);
		mButton= (Button) mView.findViewById(R.id.cancle_mark);
		mButton.setOnClickListener(this);
		
		agreeYanshi=(Button) mView.findViewById(R.id.agree_yanshi);
		refuseYanshi=(Button) mView.findViewById(R.id.refuse_yanshi);
		agreeYanshi.setOnClickListener(this);
		refuseYanshi.setOnClickListener(this);
		mView.findViewById(R.id.service_content).setOnClickListener(this);
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		mEntity = (DoctorPatient) getArguments().getSerializable("entity");
		
		if(mEntity!=null){
			ImageLoader loader=ImageLoader.getInstance();
			ImageView view= (ImageView) mView.findViewById(R.id.header_image);
			loader.displayImage(mEntity.getCustomerSex() ,mEntity.getClientIconBackground(), view);
			initData(mEntity.getOrderId(),mEntity.getCustomerId());
		}
	}
	
	/**
	 * Type=findcustomerBackOrder
		DOCTORID 医生id
		CUSTOMER_ID 客户id
		ORDER_ID 订单id
	 */
	private void initData(String ORDER_ID,String CUSTOMER_ID) {
		RequestParams params = new RequestParams();
		params.put("DOCTORID", SmartFoxClient.getLoginUserId() );
		params.put("CUSTOMER_ID",CUSTOMER_ID);
		params.put("ORDER_ID", ORDER_ID);
		params.put("Type", "queryOrderMessage");
		HttpRestClient.doHttpServiceSetServletRJ320(params,new AsyncHttpResponseHandler(getActivity()){
			@Override
			public void onSuccess(String content) {
				if(content!=null&&content.contains("error_message")){
					com.alibaba.fastjson.JSONObject jsonObject=com.alibaba.fastjson.JSONObject.parseObject(content);
					ToastUtil.showShort(jsonObject.getString("error_message"));
				}else{
					deatils = DoctorOrderDeatils.parsToEntity(content);
					if(deatils==null){
					}else{
						initDataView(deatils);
					}
				}
			};
		} );
		
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode!=getActivity().RESULT_OK)return;
		switch (requestCode) {
		case 5000:
			String content = data.getStringExtra("content");
			if(content!=null&&(!"".equals(content))){
				CANCEL_REASON=content;
				delay(deatils.getSERVICE_CUSTOMER_ID(),deatils.getORDER_ID());
			}
			break;
		}
	}
	
	
	private void initDataView(DoctorOrderDeatils deatils){
		TextView mOriderName= (TextView)mView.findViewById(R.id.name);
		mOriderName.setText(mEntity.getCustomerNickname());
		
		TextView mOriderPrice= (TextView)mView.findViewById(R.id.price);
		mOriderPrice.setText(deatils.getSERVICE_GOLD()+"元");
		
		TextView mOriderTime= (TextView)mView.findViewById(R.id.time);
		mOriderTime.setText(TimeUtil.getDemo(deatils.getSERVICE_START(),deatils.getSERVICE_END()));
		
		TextView mOriderContent= (TextView)mView.findViewById(R.id.content);
		mOriderContent.setText(deatils.getADVICE_CONTENT());
		
		//设置所享受服务 内容...
		TextView ServiceTitle=(TextView) mView.findViewById(R.id.service_title);
		ServiceTitle.setText(deatils.getSERVICE_CONTENT());
		
		prompt = (TextView) mView.findViewById(R.id.prompt);
		String strName=(!"".equals(deatils.getPATIENT_NAME()))?deatils.getPATIENT_NAME():deatils.getPAY_ACCOUNT();
		//是预约还是面访
		if("2".equals(deatils.getSERVICE_TYPE_ID())){//预约zaixian
			mView.findViewById(R.id.layout_phone).setVisibility(View.GONE);
			mView.findViewById(R.id.layout_address).setVisibility(View.GONE);
			
		}else{//面访
			mView.findViewById(R.id.layout_phone).setVisibility(View.VISIBLE);
			mView.findViewById(R.id.layout_address).setVisibility(View.VISIBLE);
			TextView mOriderPhone= (TextView)mView.findViewById(R.id.phone);
			mOriderPhone.setText(deatils.getPATIENT_PHONE());
			TextView mOriderAddress=(TextView) mView.findViewById(R.id.address);
			mOriderAddress.setText(deatils.getSERVICE_PLACE());
		}
		
		TextView titleTextV = (TextView)mView.findViewById(R.id.title_lable);
		titleTextV.setText(deatils.getSERVICE_TYPE());
		
		switch (Integer.valueOf(deatils.getSERVICE_STATUS())) {
		case 10://未支付服务列表
			mButton.setVisibility(View.GONE);
			mView.findViewById(R.id.chat_button).setVisibility(View.GONE);
			break;
		case 160:
		case 170://查看详情
			mButton.setVisibility(View.GONE);
			mView.findViewById(R.id.chat_button).setVisibility(View.VISIBLE);
			mView.findViewById(R.id.chat_button).setOnClickListener(this);
			break;
		case 150://延时请求
			prompt.setVisibility(View.VISIBLE);
			prompt.setText(strName+"向您申请延时请求，请您及时处理!");
			mButton.setVisibility(View.GONE);
			agreeYanshi.setVisibility(View.VISIBLE);
			agreeYanshi.setText("同意延时服务请求");
			refuseYanshi.setVisibility(View.VISIBLE);
			refuseYanshi.setText("拒绝延时服务请求");
			Type="AgreedToDelay";
			isYanShi=false;
			mView.findViewById(R.id.chat_button).setVisibility(View.GONE);
			mView.findViewById(R.id.chat_button).setOnClickListener(this);
			break;
		case 60://退订请求
			prompt.setVisibility(View.VISIBLE);
			prompt.setText(strName+"向您申请退订请求，请您及时处理!");
			mButton.setVisibility(View.GONE);
			agreeYanshi.setVisibility(View.VISIBLE);
			agreeYanshi.setText("同意退订请求");
			refuseYanshi.setVisibility(View.VISIBLE);
			refuseYanshi.setText("拒绝退订请求");
			isYanShi=true;
			break;
		case 185://停止服务
			Type="DoctorStopService";
			mView.findViewById(R.id.chat_button).setVisibility(View.VISIBLE);
			mButton.setText("停止服务");
			break;
		case 175:
		case 180://取消原因
			mButton.setVisibility(View.GONE);
			break;
		case 70:
		case 155:
			if("0".equals(deatils.getEXTEND_FLAG())){
			Type="DoctorsActiveDelay";
			mButton.setText("延时服务");
			}else{
				mButton.setVisibility(View.GONE);	
			}
			mView.findViewById(R.id.chat_button).setVisibility(View.VISIBLE);
			mView.findViewById(R.id.chat_button).setOnClickListener(this);
			break;
		default:
			if(Integer.valueOf(deatils.getSERVICE_STATUS())==50){
//				TimeUtil.getTimeByString(deatils.getSERVICE_START(),deatils.getSYSTEMTIME())
				if(Long.valueOf(deatils.getSERVICE_START())<=Long.valueOf(deatils.getSYSTEMTIME())){
					if("0".equals(deatils.getEXTEND_FLAG())){
					mButton.setText("延时服务");//已预约服务（50）+开始服务时间>当前系统时间
					Type="DoctorsActiveDelay";
					}else{
						mButton.setVisibility(View.GONE);	
					}
					mView.findViewById(R.id.chat_button).setVisibility(View.VISIBLE);
					mView.findViewById(R.id.chat_button).setOnClickListener(this);
				}else if(TimeUtil.formatMillion(deatils.getSERVICE_START()) > TimeUtil.formatMillion(deatils.getSYSTEMTIME())&&TimeUtil.formatMillion(deatils.getSERVICE_START()) <TimeUtil.formatMillion(deatils.getSYSTEMTIME()) +2*60*60*1000){
					mButton.setVisibility(View.GONE);	
					prompt.setVisibility(View.VISIBLE);
					prompt.setText("当前时间距预约服务开始时间已不足2个小时,不能取消预约服务");
				}else {
					mButton.setText("取消预约");
					Type="DoctorsCancel";
				}
			}else{
				mButton.setVisibility(View.INVISIBLE);	
			}
			break;
		}
	}
	
	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.title_back:
			getActivity().onBackPressed();
			break;
		case R.id.cancle_mark://取消预约
			if(("DoctorsActiveDelay").equals(Type)){//延时服务
				agreeToDelay();
			}else if(("DoctorStopService").equals(Type)){//停止服务
				delay(deatils.getSERVICE_CUSTOMER_ID(), deatils.getORDER_ID());
			}else{
				if("".equals(Type)){
					Type="DoctorsCancel";//请填写取消预约的原因，以便系统告知对方	
				}
				intent=new Intent(getActivity(),CommonExplainActivity.class);
				intent.putExtra("title", "取消预约原因");  
				startActivityForResult(intent,5000);
			}
			
			break;
		case R.id.refuse_yanshi://拒绝
			if(isYanShi){//拒绝退订
				Type="updateOrderStatus";
			}else{//拒绝延时
				Type="RefusedToDelay";
			}
			delay(deatils.getSERVICE_CUSTOMER_ID(), deatils.getORDER_ID());
			break;
		case R.id.agree_yanshi://同意
			if(!"".equals(Type)){
				delay(deatils.getSERVICE_CUSTOMER_ID(), deatils.getORDER_ID());
			}else if(isYanShi){//同意退订
				Type="doctorBackOrder";
				delay(deatils.getSERVICE_CUSTOMER_ID(), deatils.getORDER_ID());
			}else{//同意延时
				Type="AgreedToDelay";
				agreeToDelay();
			}
			break;
		case R.id.service_content:
			intent = new Intent(getActivity(),DoctorServiceActivity.class);
			intent.putExtra("ORIDERID",deatils.getORDER_ID());
			startActivity(intent);
			break;
		case R.id.chat_button:
			toChatting();
			break;
		}
	}
	
	/**
	 * 延时服务
	 */
	private void agreeToDelay(){
		if("".equals(Type)||"延时服务".equals(mButton.getText().toString())){//同意延时(或者 主动延时)
			String str=(!"".equals(deatils.getPATIENT_NAME()))?deatils.getPATIENT_NAME():deatils.getPAY_ACCOUNT();
			//之前提示:延时服务
			DoubleBtnFragmentDialog.showDefault(getFragmentManager(),  "您确定将"+str+"的服务时间延长3小时吗？", "取消", "确定", new OnDilaogClickListener() {
				@Override
				public void onDismiss(DialogFragment fragment) {
					fragment.dismissAllowingStateLoss();
				}
				@Override
				public void onClick(DialogFragment fragment, View v) {
					delay(deatils.getSERVICE_CUSTOMER_ID(),deatils.getORDER_ID());
				}
			});
		}
	}
	
	/**
	 * 请求资料 进行跳转聊天
	 */
	private void toChatting(){
		HttpRestClient.doHttpFindCustomerInfoByCustId(null, null,deatils.getENJOY_CUSTOMER_ID(),null,new ObjectHttpResponseHandler(getActivity()) {
			@Override
			public Object onParseResponse(String content) {
				try {
					JSONObject object = new JSONObject(content);
					return DataParseUtil.jsonToCustmerInfo(object);
				} catch (JSONException e) {
					return null;
				}
				}
			@Override
			public void onSuccess(int statusCode, Object response) {
				super.onSuccess(statusCode, response);
				if(response!=null)FriendHttpUtil.onItemClick(getActivity(), (CustomerInfoEntity) response);
			}
		});
	}
	
	/**
	 * 医生取消
	 * Type=DoctorsCancel
		ORDER_ID 订单id
		DOCTORID 医生id
		CUSTOMER_ID 客户id
	 * @param DOCTORID
	 * @param ORDER_ID
	 */
	protected void delay(String DOCTORID,String ORDER_ID) {
		if("".equals(Type))return;
		HttpRestClient.doHttpAgreedToDelay(CANCEL_REASON,Type,DOCTORID,SmartFoxClient.getLoginUserId(),ORDER_ID,new AsyncHttpResponseHandler(getActivity()){
			@Override
			public void onSuccess(String content) {
				try {
					JSONObject object=new JSONObject(content);
					if(object.has("error_message")){
						ToastUtil.showBasicShortToast(getActivity(), object.optString("error_message"));
					}else{
						getActivity().setResult(getActivity().RESULT_OK, getActivity().getIntent());
						getActivity().finish();
					}
				} catch (Exception e) {
				}
			};
		});
	}
}
